<template>
<!--面包屑-->
<div style="margin-bottom: 30px;">
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <router-link to="/MenuModule/MenuDisplay">菜单管理</router-link>
    </el-breadcrumb-item>
    <el-breadcrumb-item>菜单信息修改</el-breadcrumb-item>
  </el-breadcrumb>
</div>

<el-form ref="ruleFormRef" style="max-width: 600px;margin: auto;" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

<el-form-item label="菜单权限" prop="parent_id">
   <el-select v-model="form.parent_id" placeholder="请选择菜单权限">
    <el-option label="顶级菜单" :value="0"></el-option>
     <el-option v-for="item in menuSelectData" :key="item.id" :label="item.menu_name" :value="item.id"></el-option>
   </el-select>
</el-form-item>

<el-form-item label="菜单名称" prop="menu_name">
  <el-input v-model="form.menu_name" placeholder="请输入菜单名称" />
</el-form-item>

<el-form-item label="菜单Url" prop="menu_url">
  <el-input v-model="form.menu_url" placeholder="请输入菜单Url" />
</el-form-item>

<el-form-item label="授权" prop="perms">
  <el-input v-model="form.perms" placeholder="请输入授权" />
</el-form-item>

<el-form-item label="类型" prop="type">
  <el-select v-model="form.type" placeholder="请选择类型">
    <el-option label="目录" :value="0" />
    <el-option label="菜单" :value="1" />
  </el-select>
</el-form-item>

<el-form-item label="菜单图标" prop="menu_icon">
  <el-input v-model="form.menu_icon" placeholder="请输入菜单图标" />
</el-form-item>

<el-form-item label="排序" prop="order_num">
  <el-input v-model="form.order_num" placeholder="请输入排序" />
</el-form-item>

<el-form-item label="按钮" prop="permsButton">
  <el-switch v-model="form.permsButton" />
</el-form-item>

<el-form v-if="form.permsButton==true" :model="form" ref="formRef">
  <div v-for="(button, index) in form.button" :key="index">
  <el-form-item :prop="'button.' + index + '.permission_name'" label="功能名称">
    <el-input v-model="button.permission_name" placeholder="请输入功能名称" style="width: 180px;"></el-input>
  </el-form-item>
  <el-form-item :prop="'button.' + index + '.is_perms'" label="功能路径">
    <el-input v-model="button.is_perms" placeholder="请输入功能路径" style="width: 180px;"></el-input>
    <el-button type="danger" @click="removeButton(index)">删除行</el-button>
  </el-form-item>
</div>
<el-button type="primary" @click="addButton">新增行</el-button>
</el-form>

    <el-form-item>
  <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
  <el-button @click="resetForm(ruleFormRef)">取消</el-button>
</el-form-item>
</el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import {useRoute,useRouter} from 'vue-router'

//图片上传
import { Plus } from '@element-plus/icons-vue'
const handleAvatarSuccess = (val:any) => {
    form.driverLicenseImg = val
}

const route = useRoute();
const router = useRouter();
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const formRef:any = ref(null);
  
const props = {
  checkStrictly: true,
  expandTrigger: 'hover' as const,
}


onMounted(() => {
  getPermission()

  getMenuSelect()

  getMenuInfo()
})

//form表单
const form: any = reactive({
  parent_id: "",
  menu_name	: "",
  menu_url: "",
  perms	: "",
  type: "",
  menu_icon: "",
  order_num: '',
  permission_name: '',
  is_perms: '',

  button: [
        { permission_name: '', is_perms: '' } // 初始权限对象
      ]
})

//校验
const rules = reactive<FormRules>({
  parent_id: [
    { required: true, message: '请输入菜单父级', trigger: 'blur' },
  ],
  menu_name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  menu_url: [
    { required: true, message: '请输入菜单Url', trigger: 'blur' },
  ],
  // perms: [
  //   { required: true, message: '请输入授权', trigger: 'blur' },
  // ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  // menu_icon: [
  //   { required: true, message: '请输入菜单图标', trigger: 'blur' },
  // ],
  order_num:  [
    { required: true, message: '请输入排序', trigger: 'blur' },
  ],
})


//菜单select
const menuSelectData:any=ref([])
const getMenuSelect = () => {
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuSelectShow').then(res=>{
    //console.log(res);
    menuSelectData.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}

//提交修改
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 构造完整的按钮数据
      const buttonData = form.button.map((button:any) => ({
        permission_name: button.permission_name,
        is_perms: button.is_perms
      }));
 
      let roleUpdate = {
        id: route.query.id,
        parent_id: form.parent_id,
        menu_name: form.menu_name,
        menu_url: form.menu_url,
        perms: form.perms,
        type: form.type,
        menu_icon: form.menu_icon,
        order_num: form.order_num,
        button: buttonData
      };
      axios.put('http://1.117.93.87:8000/rbacxie/api/Menu/menuUpdate',roleUpdate,).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage.success("修改成功!")
        } else if (res.data.code == 2001) {
          ElMessage.error("菜单已存在")
          return
        } else {
          ElMessage.error("修改失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//角色权限树形
const RolePermissionData:any=ref([])
const getPermission=()=>{
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuTreeShow').then(res=>{
    //console.log(res);
    RolePermissionData.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}

//反填
const getMenuInfo = () => {
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuFindId?id='+route.query.id).then(res=>{
    console.log(res);
    let menuInfo=res.data.data
    form.parent_id=menuInfo.parent_id,
    form.menu_name =menuInfo.menu_name,
    form.menu_url=menuInfo.menu_url,
    form.perms =menuInfo.perms,
    form.type=menuInfo.type,
    form.menu_icon=menuInfo.menu_icon,
    form.order_num=menuInfo.order_num,
    form.permission_name=menuInfo.permission_name,
    form.is_perms=menuInfo.is_perms
      // 检查 button 数组是否有值
      if (menuInfo.button && menuInfo.button.length > 0) {
        form.permsButton = true; // 设置 permsButton 为 true
 
        // 清空 form.button 数组
        form.button = [];
 
        // 遍历 menuInfo.button 并填充 form.button
        menuInfo.button.forEach((button:any) => {
          form.button.push({
            permission_name: button.permission_name,
            is_perms: button.perms // 注意：这里可能需要调整为 button.is_perms 或其他正确的属性名，取决于你的数据结构
          });
        });
      } else {
        form.permsButton = false; // 如果没有按钮数据，则设置为 false
      }
      
  }).catch(err=>{
    console.log(err);

  })    
}

interface DomainItem {
  key: number
  value: string
}

const addButton = () => {
      form.button.push({ permission_name: '', is_perms: '' });
      // 调用更新验证规则的方法（但请注意上面的注意事项）
      // updateRules(); // 由于响应式限制，这里注释掉
    };
 
    const removeButton = (index:any) => {
      form.button.splice(index, 1);
      // 移除对应的验证规则（同样需要手动更新，但在这个示例中我们忽略了这一步）
      // 由于响应式限制，这里不直接操作 rules 对象
    };

</script>

<style scoped>

</style>